﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tomahawk.Serialization;
using System.Xml.Serialization;
using Tomahawk.Serialization.SerialBoost;

namespace Tomahawk.Runtime.Timeline
{
    public sealed class Timeline
    {
        [XmlAttribute("Name")]
        public string name;

        [XmlElement("Groups")]
        public SerializableList<SyncGroup> groups = new SerializableList<SyncGroup>();

        private Dictionary<string, SyncGroup> groupTable = new Dictionary<string, SyncGroup>();

        [XmlIgnore()]
        public SyncGroup this[string index]
        {
            get
            {
                SyncGroup value = null;
                groupTable.TryGetValue(index, out value);
                return value;
            }
        }

        public delegate Object FindTargetObject(string name);

        public Timeline() { }

        public Timeline(string name) { this.name = name; }

        public void Initialize()
        {
            foreach (SyncGroup group in groups)
            {
                groupTable.Add(group.name, group);
                group.Initialize();
            }
        }

        public void Destroy()
        {
            foreach (KeyValuePair<string, SyncGroup> group in groupTable)
            {
                group.Value.Mode = SyncGroup.PlayMode.Stop;
            }
        }

        public bool Connect(FindTargetObject callback)
        {
            bool result = true;

            foreach (KeyValuePair<string, SyncGroup> group in groupTable)
            {
                result &= group.Value.Connect(callback);
            }

            return result;
        }

        public void Update(float elapsedTime)
        {
            foreach (KeyValuePair<string, SyncGroup> group in groupTable)
            {
                group.Value.Update(elapsedTime);
            }
        }

        public T FindTrackByName<T>(string name) where T : BaseTrack
        {
            foreach (KeyValuePair<string, SyncGroup> group in groupTable)
            {
                T track = group.Value.FindTrackByName<T>(name);
                if (track != null)
                {
                    return track;
                }
            }

            return null;
        }

        public SyncGroup FindGroupByName(string name)
        {
            foreach (KeyValuePair<string, SyncGroup> group in groupTable)
            {
                if (string.Compare(group.Key, name, true) == 0)
                {
                    return group.Value;
                }
            }

            return null;
        }

    }
}
